<?php

namespace app\admin\controller;

use app\models\CampusModel;
use app\models\ClassRoomModel;
use app\models\CompanyModel;
use app\models\StudentSubjectClassModel;
use app\models\SubjectClassModel;
use app\models\TeacherModel;
use app\models\UserModel;

class Classroom extends Common
{
    /**
     * 用户管理模型.
     *
     *  @var UserModel
     */
    protected $userModel;

    /**
     * 集团模型
     * @var CompanyModel
     */
    protected $companyModel;

    /**
     * 校区管理模型.
     *
     * @var CampusModel
     */
    protected $campusModel;

    /**
     * 班课管理模型.
     *
     * @var SubjectClassModel
     */
    protected $subjectclassModel;

    /**
     * 班课学生管理模型.
     *
     * @var StudentSubjectClassModel
     */
    protected $studentsubjectclassModel;

    /**
     * 教室管理模型.
     *
     * @var ClassRoomModel
     */
    protected $classroomModel;

    /**
     * 教师管理.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function lists()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = $this->classroomModel->getClassRoomLists($param);
            $this->success('success', '', $campus, 0);
        }

        return $this->fetch();
    }

    /**
     * 添加教室.
     *
     * @return mixed
     */
    public function room_add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $data['seat_nums'] =  $data['seat_row'] * $data['seat_column'];

            //去重
            $res = $this->classroomModel->get(['campus_id' => $data['campus_id'],'class_name'=>  $data['class_name']]);
            if($res){
                $this->error('该校区已经存在该教室', null, '', 1);
            }

            if (!$this->classroomModel->save($data)) {
                $this->error('添加教室失败', null, '', 1);
            }
            $this->success('添加成功', url('Teacher/lists'), '', 1);
        }
		$where = [];
		if(get_current_type() == 4 || get_current_type() == 5){/*校区数据权限*/
			$where['id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){/*区域数据权限*/
			$where['id'] = ['in',get_current_campus_id()];
		}

        /***********集团**********/
        $company_result = $this->companyModel->select();
        $company_arr =[];
        foreach ($company_result as $key => $value){
            $company_arr[$value['id'].''] = $value['company_name'];
        }
        /*****************************/

        /*************过滤掉未分配系统账号的集团*************/
        if(get_current_type() == 1){  //超管
            $user_result = $this->userModel->where(['wtype' => 2])->select();
            $company_user_arr = [];
            foreach ($user_result as $key => $value){
                $company_user_arr[] = $value['company_id'];
            }
            $company_user_arr = array_unique($company_user_arr);
            $company_user_str = implode(',',$company_user_arr);
            $where['company_id'] = ['in',$company_user_str];
        }

        $campus = $this->campusModel->where($where)->select();  //校区
        if(get_current_type() == 1){    //超级管理员
            foreach ($campus as $key => $value){
                $value['campus_name'] =   $value['campus_name'].'【'.$company_arr[$value['company_id'].''].'】';
            }
        }

        return $this->fetch('',['campus' => $campus]);
    }


    /**
     * 教室排座.
     *
     * @return mixed
     */
    public function set_seat()
    {
        $seat_column = input('seat_column');  //列
        $seat_row = input('seat_row');  //行
        $seat_id = input('id');

        $seat_nums = $this->classroomModel->get(['id' => $seat_id])['seat_set'];//获取选中的座位

        $this->assign('seat_column', $seat_column);
        $this->assign('seat_row',  $seat_row );
        $this->assign('seat_id',  $seat_id );
        $this->assign('seat_nums',  $seat_nums );
        return $this->fetch();
    }

    /**
     * 排位.
     *
     * @return mixed
     */
    public function seat_selection()
    {

        $seat_id  = input('id'); //教室ID
        $campus_id  = input('campus_id'); //教室ID
        $class_subject_id = input('class_subject_id');  //班级ID
        $result = $this->studentsubjectclassModel->where(['campus_id'=>$campus_id,'class_subject_id'=> $class_subject_id,'room_id' => $seat_id])->select(); // 获取学生姓名
        $arr_numbers = ""; //已经选坐的学生
        $arr_number_names = ""; //已经选座的学生姓名
        $len_value = 0;  //长度
        $name_value = ""; //姓名
        $num_count = 0;  //已选个数
        foreach ($result as $key => $item){
            if($item['seat_number'] != NULL){
                $num_count ++;
                $len_now = strlen($item['student_name']);  //比较最大者
                if(($len_now - $len_value) > 0){
                    $len_value = $len_now;
                    $name_value = $item['student_name'];
                }
                $arr_numbers = $arr_numbers.$item['seat_number'].',';
                $arr_number_names = $arr_number_names.$item['student_name'].'-'.$item['seat_number'].',';
            }
        }

        $str =trim($arr_numbers);
        $arr_numbers = substr($str,0,strlen($str)-1);
        $arr_number_names = substr(trim($arr_number_names),0,trim($arr_number_names)-1);
        $seat_result = $this->classroomModel->get(['id' => $seat_id]);//获取教室信息

        $seat_already = $seat_result['seat_set'];  //可分配座位个数
        $seat_already_arr = explode(",",$seat_already);  //座位个数

        $this->assign('seat_column', $seat_result['seat_column']);
        $this->assign('seat_row',  $seat_result['seat_row'] );
        $this->assign('seat_id',  $seat_id );
        $this->assign('campus_id',  $campus_id );
        $this->assign('seat_nums',  $seat_result['seat_set'] );
        $this->assign('subject_id',  $class_subject_id );
        $this->assign('arr_numbers',  $arr_numbers );
        $this->assign('arr_number_names',  $arr_number_names);
        $this->assign('name_value',  $name_value );
        $this->assign('nums',  count($seat_already_arr) - $num_count);
        return $this->fetch();
    }

    /**
     * 编辑.
     *
     * @return mixed
     */
    public function class_edit()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $data['seat_set'] = ""; //重置锁定座位
            $data['seat_nums'] = $data['seat_column'] * $data['seat_row']; //改变行数或者列数自动更新座位数
            if (!$this->classroomModel->save($data, ['id' => $data['id']])) {
                $this->error('编辑失败', null, '', 1);
            }
            $this->success('编辑成功', url('Classroom/lists'), '', 1);
        }
    }


    /**
     * 编辑教室座位数.
     *
     * @return mixed
     */
    public function nums_edit()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if (!$this->classroomModel->save($data, ['id' => $data['id']])) {
                $this->error('编辑数量失败', null, '', 1);
            }
            $this->success('编辑成功', url('Classroom/lists'), '', 1);
        }
    }


    /**
     * 编辑教室座位列.
     *
     * @return mixed
     */
    public function column_edit()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if (!$this->classroomModel->save($data, ['id' => $data['id']])) {
                $this->error('编辑列失败', null, '', 1);
            }
            $this->success('编辑成功', url('Classroom/lists'), '', 1);
        }
    }


    /**
 * 设置教室座位数.
 *
 * @return mixed
 */

    public function choice_seat(){

        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $nums = trim($data['nums']);
            if(!$this->classroomModel->get(['id' => $data['seat_id'],'seat_set' => $nums])){
                if (!$this->classroomModel->save(['seat_set' => $nums], ['id' => $data['seat_id']])) {
                    $this->error('锁定失败', null, '', 1);
                }
            }else{
                $this->error('请先重置再锁定', null, '', 1);
            }

            $this->success('锁定成功', url('Classroom/list'), '', 1);
        }
    }


    /**
     * 复位教室座位数.
     *
     * @return mixed
     */

    public function rest_seat(){

        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if(!$this->classroomModel->get(['id' => $data['seat_id'],'seat_set' => ''])){
                    if (!$this->classroomModel->save(['seat_set' => ''], ['id' => $data['seat_id']])) {
                        $this->error('解除失败', null, '', 1);
                    }
            }else{
                $this->success('解除锁定', null, '', 1);
            }
            $this->success('解除锁定', url('Classroom/set_seat'), '', 1);
        }
    }


    /**
     * 编辑教室座位行.
     *
     * @return mixed
     */
    public function row_edit()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if (!$this->classroomModel->save($data, ['id' => $data['id']])) {
                $this->error('编辑行失败', null, '', 1);
            }
            $this->success('编辑成功', url('Classroom/lists'), '', 1);
        }
    }
	  /**
     * 导入教室表格.
     *
     * @return mixed
     */
    public function room_excel()
    {

        try {
            if (request()->isPost()){
                $file = request()->file('file');
                if($file->getInfo()['error'] == 0){
                    $filename = $file->getInfo()['name'];
                    $file_type = explode(".",$filename)[1];
                    if(strcasecmp($file_type,"Xlsx")== 0 || strcasecmp($file_type,"Xls") == 0
                        || strcasecmp($file_type,"Xml") == 0 || strcasecmp($file_type,"Ods") == 0
                        || strcasecmp($file_type,"Slk") == 0 || strcasecmp($file_type,"Gnumeric") == 0
                        || strcasecmp($file_type,"Html") == 0 || strcasecmp($file_type,"Csv") == 0){

                        $filename = 'Import_classroom_excel.'.$file_type;
                        $file->move(ROOT_PATH . 'public',$filename); //上传后的文件名
                        $excelData = readExcelFile(ROOT_PATH . 'public/'.$filename); //读表
                        if ($excelData != null) {
                            if(is_file(ROOT_PATH . 'public/'.$filename) && unlink(ROOT_PATH . 'public/'.$filename)){
                                //插入数据库
                                $data = [];
                                foreach ($excelData as $key => $value){

                                        $res_campus = $this->campusModel->get(['campus_name' => $value[4]]);
                                        if(!$res_campus){
                                            continue;
                                        }

                                        $res_room = $this->classroomModel->get(['campus_id' => $res_campus['id'],'class_name'=>  $value[0]]);
                                        if($res_room){
                                            continue;
                                        }

                                        $opt['campus_id'] = $res_campus['id']; //校区ID
                                        $opt['class_name']= $value[0];    //教室名称
                                        $opt['seat_nums']= $value[1];  //教室座位数
                                        $opt['seat_row']= $value[2];  //教室座行
                                        $opt['seat_column']= $value[3]; //教室座列
                                        $data[$key] = $opt;
                                }
                                if(count($data) > 0){
                                    $this->classroomModel->saveAll($data);
                                    return ['code' => 0, 'data' => $excelData, 'name' => $filename, 'size'=>$file->getInfo()['size']];
                                }else{
                                    return ['code' => 0, 'name' => $filename];
                                }

                            }

                        }
                    }
                }



            }

        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }
	
	
	
	
    /**
     * 删除教室
     *
     * @return mixed
     */
    public function room_del()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            if (!$this->classroomModel->where(['id' => input('id')])->delete()) {
                $this->error('删除教室失败', null, '', 1);
            }
            $this->success('删除成功', url('Teacher/lists'), '', 1);
        }
    }

    /**
     * 更改教室状态.
     *
     * @return mixed
     */
    public function room_status()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if (1 == $data['status']) {
                $msg = '启用';
            } else {
                $msg = '禁用';
            }
            if (!$this->classroomModel->save($data, ['id' => $data['id']])) {
                $this->error($msg.'更改失败', null, '', 1);
            }
            $this->success($msg.'成功', '', '', 1);
        }
    }


    /**
     * 获取学生列表
     *
     * @return mixed
     */
    public function getstudentlist(){
        $id = input('id'); //选课排课id
        $room_id = input('room_id'); //教室id
        $campus_id = input('campus_id');
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = $this->studentsubjectclassModel->getStudentLists($param,$id,$room_id,$campus_id);
            $this->success('success', '', $campus, 0);
        }

        return $this->fetch();
    }


    /**
     * 取消选座位数.
     *
     * @return mixed
     */

    public function cancle_seat(){

        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $class_subject_id = $data['class_subject_id'];  //课程ID
            $room_id = $data['room_id'];
            $seat_number = $data['seat_number'];  //座位编号
            if (!$this->studentsubjectclassModel->where(['room_id' => $room_id, 'seat_number' => $seat_number, 'class_subject_id' => $class_subject_id])->Update(['seat_number' => NULL])) {
                $this->error('取消失败', null, '', 1);
            }


            $this->success('取消成功', url('Classroom/list'), '', 1);
        }
    }

    /**
     * 设置选座位数.
     *
     * @return mixed
     */

    public function set_student_seat(){

        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $id = $data['student_id'];  //学生ID
            $seat_number = $data['seat_number']; //座位编号
            if (!$this->studentsubjectclassModel->save(['seat_number' => $seat_number], ['id' => $id])) {
                    $this->error('选座失败', null, '', 1);
                }


            $this->success('选座成功', url('Classroom/list'), '', 1);
        }
    }


    /**
     * 重置选座位数.
     *
     * @return mixed
     */

    public function reset_student_seat(){

        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $class_subject_id = $data['class_subject_id']; //选课id
            if (!$this->studentsubjectclassModel->save(['seat_number' => NULL], ['class_subject_id' => $class_subject_id])) {
                $this->success('重置成功', url('Classroom/list'), '', 1);
            }
            $this->success('重置成功', url('Classroom/list'), '', 1);
        }
    }



    /**
     *  实例化.
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->classroomModel = new ClassRoomModel();
        $this->studentsubjectclassModel = new StudentSubjectClassModel();
        $this->subjectclassModel = new SubjectClassModel();
        $this->campusModel = new CampusModel();
        $this->companyModel = new CompanyModel();
        $this->userModel = new UserModel();
    }
}
